<?php
/**
 * 将一些常用的功能定义到Ivf类里公用
 **/
class Ivf{

    static function httpGet($url, $params = array(), $timeout = 5){
        if(!empty($params)){
            $url .= '?' . http_build_query($params);
        }
        return self::curlRequest($url, null, $timeout);
    }

    static function httpPost($url, $params = array(), $timeout = 5){
        if(!is_array($params)){
            $params = (array)$params;
        }
        return self::curlRequest($url, $params, $timeout);
    }

    private static function curlRequest($url, $postFields = null, $timeout = 5){
        $ch = curl_init($url);
        $options = array(
            CURLOPT_AUTOREFERER => 1,
            CURLOPT_FOLLOWLOCATION => 1,
            CURLOPT_HEADER =>  0,
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_SSL_VERIFYPEER => 0,
            CURLOPT_TIMEOUT => $timeout,
            CURLOPT_USERAGENT => 'ivf52.com',
        );
        curl_setopt_array($ch, $options);
        if(is_array($postFields) && !empty($postFields)){
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
        }
        $response = curl_exec($ch);
        if($response === false){
            //curl fail
            $exception = new Exception(curl_error($ch) . ' for url ' . $url , curl_errno($ch));
            curl_close($ch);
            throw $exception;
        }else{
            curl_close($ch);
            return $response;
        }
    }

    static function isDatetime($param = '', $format = 'Y-m-d H:i:s') { 
        return date($format, strtotime($param)) === $param; 
    } 

    static function trimall($str)//删除空格 
    { 
        $oldchar=array(" ","　","\t","\n","\r"); 
        $newchar=array("","","","",""); 
        return str_replace($oldchar,$newchar,$str);

    }
    
    static function getClientIp(){
        $ip=false;  
        if(!empty($_SERVER["HTTP_CLIENT_IP"])){  
            $ip = $_SERVER["HTTP_CLIENT_IP"];  
        }  
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {  
            $ips = explode (", ", $_SERVER['HTTP_X_FORWARDED_FOR']);  
            if ($ip) {
                array_unshift($ips, $ip); $ip = FALSE;
            }
            for ($i = 0; $i < count($ips); $i++) {  
                if (!eregi ("^(10|172\.16|192\.168)\.", $ips[$i])) {  
                    $ip = $ips[$i];  
                    break;  
                }  
            }  
        }  
        return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
    }

    static function new_addslashes($string){
        if(!is_array($string)) return addslashes($string);
        foreach($string as $key => $val) $string[$key] = new_addslashes($val);
        return $string;
    }

    static function new_stripslashes($string){
        if(!is_array($string)) return stripslashes($string);
        foreach($string as $key => $val) $string[$key] = new_stripslashes($val);
        return $string;
    }

    static function create_small_image($imgsrc,$imgdst){
        list($width,$height,$type)=getimagesize($imgsrc);
        $new_width = ($width > 600 ? $width * 0.5 : $width)*0.9;
        $new_height = ($width > 600 ? $height * 0.5 : $height)*0.9;
        switch($type){
            case 1:
                $giftype=check_gifcartoon($imgsrc);
                if($giftype){
                    header('Content-Type:image/gif');
                    $image_wp=imagecreatetruecolor($new_width, $new_height);
                    $image = imagecreatefromgif($imgsrc);
                    imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
                    //75代表的是质量、压缩图片容量大小
                    imagejpeg($image_wp, $imgdst,75);
                    imagedestroy($image_wp);
                }
                break;
            case 2:
                header('Content-Type:image/jpeg');
                $image_wp=imagecreatetruecolor($new_width, $new_height);
                $image = imagecreatefromjpeg($imgsrc);
                imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
                //75代表的是质量、压缩图片容量大小
                imagejpeg($image_wp, $imgdst,75);
                imagedestroy($image_wp);
                break;
            case 3:
                header('Content-Type:image/png');
                $image_wp=imagecreatetruecolor($new_width, $new_height);
                $image = imagecreatefrompng($imgsrc);
                imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
                //75代表的是质量、压缩图片容量大小
                imagejpeg($image_wp, $imgdst,75);
                imagedestroy($image_wp);
                break;
        }
    }

    //二维数组查询某个值是否存在
    static function deep_in_array($value, $array) {   
        foreach($array as $item) {   
            if(!is_array($item)) {   
                if ($item == $value) {  
                    return true;  
                } else {  
                    continue;   
                }  
            }   
                
            if(in_array($value, $item)) {  
                return true;      
            } else if(Ivf::deep_in_array($value, $item)) {  
                return true;      
            }  
        }   
        return false;   
    } 
    //二维数组排序
    static function my_sort($arrays,$sort_key,$sort_order=SORT_ASC,$sort_type=SORT_REGULAR){  
        if(is_array($arrays)){  
            foreach ($arrays as $array){  
                if(is_array($array)){  
                    $key_arrays[] = $array[$sort_key];  
                }else{  
                    return false;  
                }  
            }  
        }else{  
            return false;  
        } 
        array_multisort($key_arrays,$sort_order,$sort_type,$arrays);  
        return $arrays;  
    }
    static function mobileMosaic($mobile){
        return preg_replace('/(\d{3})\d{5}(\d{3})/', '${1}*****${2}', $mobile);
    }

    static function str_n_pos($str,$find,$n) { 
        preg_match_all("/($find)/",$str,$search_result, PREG_OFFSET_CAPTURE); 
        $pos = isset($search_result[1][$n-1][1]) ? $search_result[1][$n-1][1] : false;//"错误! 字符串中有且仅有". count($search_result[1])."个字符:" . $find; 
        return $pos; 
    }

    //中英文，数字，下划线
    static function checkUsernameCharacters($username){
        $len = strlen($username);
        if (empty($username) || $len < 2 || $len > 20 || !preg_match('/^[\w_\x{3300}-\x{9fff}\x{f900}-\x{faff}]{2,20}$/u', $username)) {
            return false;
        }
        return true;
    }

    static function  random($length, $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'){
        $hash = '';
        $max = strlen($chars) - 1;
        for($i = 0; $i < $length; $i++){
            $hash .= $chars[mt_rand(0, $max)];
        }
        return $hash;
    }

    /**
     * 导出excel
     *
     * @param int $expTitle 文件名称
     * @param string $expCellName 列名
     * @param array $expTableData 值
     *
     * @return mixed
     */
    static function exportExcel($expTitle,$expCellName,$expTableData){
        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle); 
        $fileName = $xlsTitle.date('_YmdHis');
        $cellNum = count($expCellName);
        $dataNum = count($expTableData);
        App::import('Vendor', 'Excel/PHPExcel');   
 
        $objPHPExcel = new PHPExcel();
        $cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T');

        //$objPHPExcel->getActiveSheet(0)->mergeCells('A1:'.$cellName[$cellNum-1].'1');//合并单元格 
        for($i=0;$i<$cellNum;$i++){   
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'1', $expCellName[$i][1]); 
        }
        
        for($i=0;$i<$dataNum;$i++){
          for($j=0;$j<$cellNum;$j++){ 
            $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+2), $expTableData[$i][$expCellName[$j][0]]);
          }             
        }
        ob_end_clean();
        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$fileName.'.xls"');
        header("Content-Disposition:attachment;filename=".$fileName.".xls");//attachment新窗口打印inline本窗口打印
        $objWriter =  new PHPExcel_Writer_Excel5($objPHPExcel);  
        $objWriter->save('php://output'); 
        exit;   
    }

    /** 
     * 把返回的数据集转换成Tree 
     * @param array $attr 要转换的数据集 
     * @param string $pk  主键字段 
     * @param string $pid parent
     * @param string $root 顶级值
     * @return array  
     */  
    static function Totree($list, $pk='id', $pid = 'parent_id', $root = 0) {  
        $tree = array();  
        if(is_array($list)) {   
            $refer = array();  
            foreach ($list as $key => $data) {  
                $refer[$data[$pk]] =& $list[$key];  
            }  
            foreach ($list as $key => $data) {   
                $parentId =  $data[$pid];  
                if ($root == $parentId) {  
                    $tree[] =& $list[$key];  
                }else{  
                    if (isset($refer[$parentId])) {  
                        $parent =& $refer[$parentId];  
                        $parent['_child'][] =& $list[$key];  
                    }  
                }  
            }  
        }    
        return $tree;  
    } 

    /**
     * 验证手机号是否正确
     *
     * @param string $mobile
     *
     * @return bool
     */
    static function isMobile($mobile)
    {
        return preg_match('#^(13[0-9]|14[0-9]|15[0-9]|18[0-9]|17[0-9])\d{8}$#', $mobile) ? true : false;
    }

    //检查昵称是否有关键词
    static function hasDangerNickname($nickname){
        $limit = array('管理','管_理', '工作','工_作','试管邦','试_管邦','试管_邦','人员','人_员');
        foreach ($limit as $key => $val) {
            $res = strpos($nickname, $val);
            if(is_numeric($res)){
                return true;
            }
        }
        return false;
    }


    //生成攻略今日发布数
    static function planCount(){ 
        App::uses('RedisServer', 'Lib');
        $_redis=new RedisServer();
        
        $randCount=RedisServer::REDIS_KEY_PLANS_ADD_COUNT;  
        $issetPlan=$_redis->exists($randCount);
        if(empty($issetPlan)){
            $plan_num=rand(10,100);  //随机10-100之间
            $expire_time = strtotime(date('Y-m-d',strtotime("+1 day"))) - time(); //当日剩余时间   
            $_redis->set($randCount, intval($plan_num),$expire_time);  
        }   
        $randCount = $_redis->get($randCount); 
        return (int)$randCount;
    }


    //生成试管助手测试数
    static function aideCount($act='',$anum=0){
        App::uses('RedisServer', 'Lib');
        $_redis=new RedisServer();
        
        $randCount=RedisServer::REDIS_KEY_AIDE_ADD_COUNT;  
        $issetPlan=$_redis->exists($randCount);
        if(empty($issetPlan)){
            $aide_num=rand(1,20);  //随机10-100之间
            $expire_time = strtotime(date('Y-m-d',strtotime("+2 day"))) - time(); //当日剩余时间    
            $_redis->set($randCount, intval(1289+$aide_num),$expire_time); 
        }  
        $randCount = $_redis->get($randCount); 
        if($act=='add'){ 
            $expire_time = strtotime(date('Y-m-d',strtotime("+2 day"))) - time(); //当日剩余时间    
            $_redis->set(RedisServer::REDIS_KEY_AIDE_ADD_COUNT, intval($randCount+$anum),$expire_time); 
            $randCount = $_redis->get(RedisServer::REDIS_KEY_AIDE_ADD_COUNT); 
        } 
        return (int)$randCount;
    }

    /**
     *   实现PC,PAD,WAP截取固定字符方法
     */
    static function getLittleText($string,$type="pc",$pclength=70, $waplength=35,$fuhao="...") {
          if($type=="pc" || $type=="ipad" || $type=="ipod")
              return Ivf::getSubstr($string, 0, $pclength);
          else
              return Ivf::getSubstr($string, 0, $waplength); 
    }

    /**
     *   实现中文字串截取无乱码的方法
     */
    static function getSubstr($string, $start, $length,$fuhao="...") {
          if(mb_strlen($string,'utf-8')>$length){
              $str = mb_substr($string, $start, $length,'utf-8');
              return $str.$fuhao;
          }else{
              return $string;
          }
    }

    /**
     * 格式化时间
     *
     * @param string $atime
     * @param string $format
     *
     * @return bool|string
     */
    static function formatTime($atime, $format = 'Y-m-d')
    {
        if (is_string($atime)) {
            $atime = strtotime($atime);
        }
        $time = time();
        $timeDiff = $time - $atime;
        if ($timeDiff < 60) {
            $formatTime = "1分钟前";
        } elseif ($timeDiff > 60 && $timeDiff < 3600) {
            $formatTime = floor($timeDiff / 60) . "分钟前";
        } elseif ($timeDiff > 3600 && $timeDiff < 3600 * 24) {
            $formatTime = floor($timeDiff / 3600) . "小时前";
        } elseif ($timeDiff > 3600 * 24 && $timeDiff < 3600 * 24 * 30) {
            $formatTime = floor($timeDiff / (3600 * 24)) . "天前";
        } else {
            $formatTime = date($format, $atime);
        }
        return $formatTime;
    }

     
    static function upload_img_64base($save_url='/uploads/attached/',$base64_url,$dir_name='image')
    { 
        $php_path = dirname(dirname(__FILE__)).'/webroot/'; 
        //文件保存目录路径  
        $save_path = $php_path . $save_url; 

        if (!file_exists($save_path)) { 
            mkdir($save_path);
        }  
         //创建文件夹  
        if ($dir_name !== '') {
            $save_path .= $dir_name . "/"; 
            $save_url .= $dir_name . "/";
            if (!file_exists($save_path)) {
                mkdir($save_path);
            }
        }
        $ymd = date("Ymd");
        $save_path .= $ymd . "/"; 
        $save_url .= $ymd . "/";
        if (!file_exists($save_path)) {
            mkdir($save_path);
        }
        //新文件名
        $save_name = date("YmdHis") . '_' . rand(10000, 99999).'.jpg'; 
        $base64_body = substr(strstr($base64_url,','),1);
        $data= base64_decode($base64_body); 
        file_put_contents($save_path.$save_name,$data); 
        return $save_url.$save_name;
    }  

    static function upload_excel($save_url='/uploads/excel/',$dir_name='users')
    { 
        $php_path = dirname(dirname(__FILE__)).'/webroot/'; 
        //文件保存目录路径  
        $save_path = $php_path . $save_url; 

        if (!file_exists($save_path)) { 
            mkdir($save_path);
        }  
         //创建文件夹  
        if ($dir_name !== '') {
            $save_path .= $dir_name . "/"; 
            $save_url .= $dir_name . "/";
            if (!file_exists($save_path)) {
                mkdir($save_path);
            }
        }
        $ymd = date("Ymd");
        $save_path .= $ymd . "/"; 
        $save_url .= $ymd . "/";
        if (!file_exists($save_path)) {
            mkdir($save_path);
        }
        //新文件名
        $save_name = date("YmdHis") . '_' . rand(10000, 99999).'.jpg'; 
        $base64_body = substr(strstr($base64_url,','),1);
        $data= base64_decode($base64_body); 
        file_put_contents($save_path.$save_name,$data); 
        return $save_url.$save_name;
    } 
     

    static function uploadImg($save_url='/uploads/attached/'){  
        $dataRes['status']=4002;
        $php_path = dirname(dirname(__FILE__)).'/webroot/'; 
        //文件保存目录路径  
        $save_path = $php_path . $save_url; 

        if (!file_exists($save_path)) { 
            mkdir($save_path);
        } 

        //定义允许上传的文件扩展名
        $ext_arr = array(
            'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
            // 'flash' => array('swf', 'flv'),
            // 'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'),
            // 'file' => array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2'),
        );
        //最大文件大小
        $max_size = 10000000; //10MB
        $save_path = realpath($save_path) . '/';
        //PHP上传失败
        if (!empty($_FILES['imgFile']['error'])) {
            switch($_FILES['imgFile']['error']){
                case '1':
                    $error = '超过php.ini允许的大小。';
                    break;
                case '2':
                    $error = '超过表单允许的大小。';
                    break;
                case '3':
                    $error = '图片只有部分被上传。';
                    break;
                case '4':
                    $error = '请选择图片。';
                    break;
                case '6':
                    $error = '找不到临时目录。';
                    break;
                case '7':
                    $error = '写文件到硬盘出错。';
                    break;
                case '8':
                    $error = 'File upload stopped by extension。';
                    break;
                case '999':
                default:
                    $error = '未知错误。';
            } 
            $dataRes['message']=$error;
            return $dataRes; 
        }
        if(!empty($_FILES['file_data'])){ //bootstrap-fileinput
            $_FILES['imgFile'] = $_FILES['file_data'];
        }
        //有上传文件时
        if (empty($_FILES) === false) {
            //原文件名
            $file_name = $_FILES['imgFile']['name'];
            //服务器上临时文件名
            $tmp_name = $_FILES['imgFile']['tmp_name'];
            //文件大小
            $file_size = $_FILES['imgFile']['size'];
            //检查文件名
            if (!$file_name) { 
                $dataRes['message']="请选择文件。";
                return $dataRes;  
            }
            //检查目录
            if (@is_dir($save_path) === false) {  
                $dataRes['message']="上传目录不存在。";
                return $dataRes;   
            }
            //检查目录写权限
            if (@is_writable($save_path) === false) {  
                $dataRes['message']="上传目录没有写权限。";
                return $dataRes;    
            }
            //检查是否已上传
            if (@is_uploaded_file($tmp_name) === false) {  
                $dataRes['message']="上传失败。";
                return $dataRes;    
            }
            //检查文件大小
            if ($file_size > $max_size) { 
                $dataRes['message']="上传文件大小超过限制。";
                return $dataRes;     
            }
            //检查目录名
            $dir_name = empty($_GET['dir']) ? 'image' : trim($_GET['dir']);
            if (empty($ext_arr[$dir_name])) { 
                $dataRes['message']="目录名不正确。";
                return $dataRes;      
            }
            //获得文件扩展名
            $temp_arr = explode(".", $file_name);
            $file_ext = array_pop($temp_arr);
            $file_ext = trim($file_ext);
            $file_ext = strtolower($file_ext);
            //检查扩展名
            if (in_array($file_ext, $ext_arr[$dir_name]) === false) { 
                $dataRes['message']="上传文件扩展名是不允许的扩展名。\n只允许" . implode(",", $ext_arr[$dir_name]) . "格式。";
                return $dataRes;       
            }
            //创建文件夹
            if ($dir_name !== '') {
                $save_path .= $dir_name . "/";
                $save_url .= $dir_name . "/";
                if (!file_exists($save_path)) {
                    mkdir($save_path);
                }
            }
            $ymd = date("Ymd");
            $save_path .= $ymd . "/";
            $save_url .= $ymd . "/";
            if (!file_exists($save_path)) {
                mkdir($save_path);
            }
            //新文件名
            $new_file_name = date("YmdHis") . '_' . rand(10000, 99999) . '.' . $file_ext;
            //移动文件
            $file_path = $save_path . $new_file_name;
            if (move_uploaded_file($tmp_name, $file_path) === false) {
                $dataRes['message']="上传文件失败。";
                return $dataRes;       
            }
            @chmod($file_path, 0644); 
            $file_url = $save_url . $new_file_name; 
            $dataRes['status']=200; 
            $dataRes['url']=$file_url; 
            $dataRes['save_url']=$save_url; 
            $dataRes['save_name']=$new_file_name; 
            return $dataRes;  
        } 
        $dataRes['message']="上传文件不能为空。";
        return $dataRes;  
    }

    static function cropImg($params,$save_url='/uploads/attached/'){
        $php_path = dirname(dirname(__FILE__)).'/webroot/'; 
        //文件保存目录路径  
        $save_path = $php_path . $save_url; 

        if (!file_exists($save_path)) { 
            mkdir($save_path);
        } 

        $imgUrl = $params['imgUrl'];
        // original sizes
        $imgInitW = $params['imgInitW'];
        $imgInitH = $params['imgInitH'];
        // resized sizes
        $imgW = $params['imgW'];
        $imgH = $params['imgH'];
        // offsets
        $imgY1 = $params['imgY1'];
        $imgX1 = $params['imgX1'];
        // crop box
        $cropW = $params['cropW'];
        $cropH = $params['cropH'];
        // rotation angle
        $angle = $params['rotation'];

        $jpeg_quality = 100;

        //创建文件夹
        $dir_name='image';
        if ($dir_name !== '') {
            $save_path .= $dir_name . "/"; 
            $save_url .= $dir_name . "/";
            if (!file_exists($save_path)) {
                mkdir($save_path);
            }
        }
        $ymd = date("Ymd");
        $save_path .= $ymd . "/"; 
        $save_url .= $ymd . "/";
        if (!file_exists($save_path)) {
            mkdir($save_path);
        }
        //新文件名
        $new_file_name = date("YmdHis") . '_' . rand(10000, 99999);
        $output_filename = $save_path . $new_file_name;
        $output_url=$save_url .$new_file_name;

       // $output_filename = "temp/croppedImg_".rand(); 

        $what = getimagesize($imgUrl);

        switch(strtolower($what['mime']))
        {
            case 'image/png':
                $img_r = imagecreatefrompng($imgUrl);
                $source_image = imagecreatefrompng($imgUrl);
                $type = '.png';
                break;
            case 'image/jpeg':
                $img_r = imagecreatefromjpeg($imgUrl);
                $source_image = imagecreatefromjpeg($imgUrl);
                error_log("jpg");
                $type = '.jpeg';
                break;
            case 'image/gif':
                $img_r = imagecreatefromgif($imgUrl);
                $source_image = imagecreatefromgif($imgUrl);
                $type = '.gif';
                break;
            default: die('image type not supported');
        } 

        if(!is_writable(dirname($output_filename))){
            $response = Array(
                "status" => 'error',
                "message" => 'Can`t write cropped File'
            );  
        }else{ 
            // resize the original image to size of editor
            $resizedImage = imagecreatetruecolor($imgW, $imgH);
            imagecopyresampled($resizedImage, $source_image, 0, 0, 0, 0, $imgW, $imgH, $imgInitW, $imgInitH);
            // rotate the rezized image
            $rotated_image = imagerotate($resizedImage, -$angle, 0);
            // find new width & height of rotated image
            $rotated_width = imagesx($rotated_image);
            $rotated_height = imagesy($rotated_image);
            // diff between rotated & original sizes
            $dx = $rotated_width - $imgW;
            $dy = $rotated_height - $imgH;
            // crop rotated image to fit into original rezized rectangle
            $cropped_rotated_image = imagecreatetruecolor($imgW, $imgH);
            imagecolortransparent($cropped_rotated_image, imagecolorallocate($cropped_rotated_image, 0, 0, 0));
            imagecopyresampled($cropped_rotated_image, $rotated_image, 0, 0, $dx / 2, $dy / 2, $imgW, $imgH, $imgW, $imgH);
            // crop image into selected area
            $final_image = imagecreatetruecolor($cropW, $cropH);
            imagecolortransparent($final_image, imagecolorallocate($final_image, 0, 0, 0));
            imagecopyresampled($final_image, $cropped_rotated_image, 0, 0, $imgX1, $imgY1, $cropW, $cropH, $cropW, $cropH);
            // finally output png image
            //imagepng($final_image, $output_filename.$type, $png_quality);
            imagejpeg($final_image, $output_filename.$type, $jpeg_quality);
            $response = Array(
                "status" => 'success',
                "url" => $output_url.$type
            );
        }
        return $response;
    }

    // 按指定大小生成缩略图，而且不变形，缩略图函数 
   static function thumb_pic($f, $t, $tw=500, $th=500){ 
        //验证参数  
        if(!is_string($f) || !is_string($t)){  
                return false;  
        }    
        $temp = array(1=>'gif', 2=>'jpeg', 3=>'png', 4=>'wbmp');
 
        list($fw, $fh, $tmp) = getimagesize($f);
 
        if(!$temp[$tmp]){
                return false;
        }
        $tmp = $temp[$tmp];
        $infunc = "imagecreatefrom$tmp";
        $outfunc = "image$tmp";
 
        $fimg = $infunc($f);
 
        // 使缩略后的图片不变形，并且限制在 缩略图宽高范围内
        if($fw/$tw > $fh/$th){
            $th = $tw*($fh/$fw);
        }else{
            $tw = $th*($fw/$fh);
        }
 
        $timg = imagecreatetruecolor($tw, $th);
        imagecopyresampled($timg, $fimg, 0,0, 0,0, $tw,$th, $fw,$fh);
        if($outfunc($timg, $t)){
                return true;
        }else{
                return false;
        }
    }
    
    
    //获取平台
    static function getOSInfo($useragent = ''){
        // iphone  
        $is_iphone  = strripos($useragent,'iphone');  
        if($is_iphone){  
            return 'IOS';  
        }  
        // android  
        $is_android    = strripos($useragent,'android');  
        if($is_android){  
            return 'Android';  
        }  
        // 微信  
        $is_weixin  = strripos($useragent,'micromessenger');  
        if($is_weixin){  
            return 'weixin';  
        }  
        // ipad  
        $is_ipad    = strripos($useragent,'ipad');  
        if($is_ipad){  
            return 'ipad';  
        }  
        // ipod  
        $is_ipod    = strripos($useragent,'ipod');  
        if($is_ipod){  
            return 'ipod';  
        }  
        // pc电脑  
        $is_pc = strripos($useragent,'windows nt');  
        if($is_pc){  
            return 'pc';  
        }  
    }

    //获取手机型号
    static function getOSBrand($user_agent = ''){
        if (stripos($user_agent, "iPhone")!==false) {
            $brand = 'iPhone';
        } else if (stripos($user_agent, "SAMSUNG")!==false || stripos($user_agent, "Galaxy")!==false || strpos($user_agent, "GT-")!==false || strpos($user_agent, "SCH-")!==false || strpos($user_agent, "SM-")!==false) {
            $brand = '三星';
        } else if (stripos($user_agent, "Huawei")!==false || stripos($user_agent, "Honor")!==false || stripos($user_agent, "H60-")!==false || stripos($user_agent, "H30-")!==false) {
            $brand = '华为';
        } else if (stripos($user_agent, "Lenovo")!==false) {
            $brand = '联想';
        } else if (strpos($user_agent, "MI-ONE")!==false || strpos($user_agent, "MI 1S")!==false || strpos($user_agent, "MI 2")!==false || strpos($user_agent, "MI 3")!==false || strpos($user_agent, "MI 4")!==false || strpos($user_agent, "MI-4")!==false) {
            $brand = '小米';
        } else if (strpos($user_agent, "HM NOTE")!==false || strpos($user_agent, "HM201")!==false) {
            $brand = '红米';
        } else if (stripos($user_agent, "Coolpad")!==false || strpos($user_agent, "8190Q")!==false || strpos($user_agent, "5910")!==false) {
            $brand = '酷派';
        } else if (stripos($user_agent, "ZTE")!==false || stripos($user_agent, "X9180")!==false || stripos($user_agent, "N9180")!==false || stripos($user_agent, "U9180")!==false) {
            $brand = '中兴';
        } else if (stripos($user_agent, "OPPO")!==false || strpos($user_agent, "X9007")!==false || strpos($user_agent, "X907")!==false || strpos($user_agent, "X909")!==false || strpos($user_agent, "R831S")!==false || strpos($user_agent, "R827T")!==false || strpos($user_agent, "R821T")!==false || strpos($user_agent, "R811")!==false || strpos($user_agent, "R2017")!==false) {
            $brand = 'OPPO';
        } else if (strpos($user_agent, "HTC")!==false || stripos($user_agent, "Desire")!==false) {
            $brand = 'HTC';
        } else if (stripos($user_agent, "vivo")!==false) {
            $brand = 'vivo';
        } else if (stripos($user_agent, "K-Touch")!==false) {
            $brand = '天语';
        } else if (stripos($user_agent, "Nubia")!==false || stripos($user_agent, "NX50")!==false || stripos($user_agent, "NX40")!==false) {
            $brand = '努比亚';
        } else if (strpos($user_agent, "M045")!==false || strpos($user_agent, "M032")!==false || strpos($user_agent, "M355")!==false) {
            $brand = '魅族';
        } else if (stripos($user_agent, "DOOV")!==false) {
            $brand = '朵唯';
        } else if (stripos($user_agent, "GFIVE")!==false) {
            $brand = '基伍';
        } else if (stripos($user_agent, "Gionee")!==false || strpos($user_agent, "GN")!==false) {
            $brand = '金立';
        } else if (stripos($user_agent, "HS-U")!==false || stripos($user_agent, "HS-E")!==false) {
            $brand = '海信';
        } else if (stripos($user_agent, "Nokia")!==false) {
            $brand = '诺基亚';
        } else {
            $brand = '其他手机';
        } 
        return $brand; 
    }

}